package cn.virens.config;

import org.dromara.hutool.core.convert.ConvertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.nio.charset.Charset;
import java.util.Optional;
import java.util.function.Consumer;

@Configuration
public abstract class AbstractSpringConfig implements EnvironmentAware {
    protected static Logger logger = LoggerFactory.getLogger("cn.virens.Config");

    protected static final Charset charset = Charset.forName("UTF-8");

    protected Environment environment;

    /**
     * 从环境变量中获取配置
     */
    protected String property(String key) {
        return environment.getProperty(key);
    }

    /**
     * 从环境变量中获取配置
     */
    protected int property(String key, int defaultValue) {
        return ConvertUtil.toInt(property(key), defaultValue);
    }

    /**
     * 从环境变量中获取配置
     */
    protected String property(String key, String defaultValue) {
        return environment.getProperty(key, defaultValue);
    }

    /**
     * 从环境变量中获取配置
     */
    protected <T> void property(String key, Class<T> clazz, Consumer<T> consumer) {
        Optional.ofNullable(property(key)).filter(propertyVal -> {
            return propertyVal != null && !propertyVal.isEmpty();
        }).map(v -> convert(clazz, v)).ifPresent(consumer);
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    private static <T> T convert(Class<T> clazz, String value) {
        return ConvertUtil.convertWithCheck(clazz, value, null, true);
    }

}
